<?php
// use the dPFramework to have easy database operations (store, delete etc.) by using its ObjectOrientedDesign
// therefore we have to create a child class for the module quotations

// a class named (like this) in the form: module/module.class.php is automatically loaded by the dPFramework

/**
 *	@package dotProject
 *	@subpackage modules
 *	@version $Revision: 1.0 $
*/

// include the powerful parent class that we want to extend for quotations
require_once($AppUI->getSystemClass('dp'));		// use the dPFramework for easy inclusion of this class here
require_once($AppUI->getMasterDataClass('mdstatus'));
require_once($AppUI->getMasterDataClass('mdtype'));
require_once ($AppUI->getModuleClass('companies'));
require_once (DP_BASE_DIR . "/modules/masterdata/sequences/sequences.class.php");

// create Constant
define('ACTIVE_VAL', '1'); // Khach hang xac nhan
define('ACTIVE_KEY', 'QuotationConfirmed');
define('COMPLETED_VAL', '2'); // Nhung quotation da het han su dung
define('COMPLETED_KEY', 'QuotationCompleted');
define('PROPOSED_KEY', 'QuotationProposed');
define('NORMAL_VAL', '0');
define('AUTO_APPLY_VAL', '0'); // Use in case CRUD quotation line
define('MANUAL_APPLY_VAL', '1'); // Use in case CRUD quotation line
define('PUBLIC_PAGE', 'm=public&a=access_denied');

/**
 * The Quotations Class
 */
class CQuotations extends CDpObject {
	// link variables to the quotations object (according to the existing columns in the database table quotations)
	// use NULL for a NEW object, so the database automatically assigns an unique id by 'NOT NULL'-functionality
	var $quote_id = NULL;
	var $quote_code = NULL;
	var $quote_name = NULL;
	var $quote_customer = NULL;
	var $quote_supplier = NULL;
	var $quote_status = NULL;
	var $quote_type = NULL;
	var $quote_shipping_type = NULL;
	var $quote_remarks = NULL;
	var $quote_currency = NULL;
	var $quote_exchange_rate = NULL;
	var $quote_completed = 0;
	var $quote_start_date = NULL;
	var $quote_expire_date = NULL;
	var $quote_version = NULL;
	//var $quote_attach

	// the constructor of the CEinstein class, always combined with the table name and the unique key of the table
	function CQuotations(){
		$joins = array(
			array( 'label' => 'Tasks', 'name' => 'tasks', 'idfield' => 'task_id', 'joinfield' => 'task_quotation' ),
		);
		$this->CDpObject('quotations', 'quote_id', 'quote_code', $joins, 'quotations');
	}

	function getList(){
		$sql = 'Select * from quotations';
		//db_loadHash($sql, $result);
		return db_loadHashList($sql);
	}

	function getQuotationById($uid, $quoteId){
		$q  = new DBQuery;
		$q->createTemp('qtype');
		$q->addTable('md_type');
		$q->addQuery('type_id as qtype_id, name as qtype_name');
		$q->addWhere("type = 'Quotation'");
		$q->exec();
		$q->clear();

		$q  = new DBQuery;
		$q->createTemp('stype');
		$q->addTable('md_type');
		$q->addQuery('type_id as stype_id, name as stype_name');
		$q->addWhere("type = 'ShippingType'");
		$q->exec();
		$q->clear();

		$q  = new DBQuery;
		$q->addTable('quotations');
		$q->leftJoin('companies', 'c', 'quotations.quote_customer = c.company_id');
		$q->leftJoin('md_status', 'stat', 'quotations.quote_status = stat.status_id');
		$q->leftJoin('md_currency', 'curr', 'quotations.quote_currency = curr.currency_id');
		$q->leftJoin('suppliers', 'supp', 'quotations.quote_supplier = supp.sup_id');
		$q->leftJoin('stype', 'stype', 'quotations.quote_shipping_type = stype.stype_id');
		$q->leftJoin('qtype', 'qtype', 'quotations.quote_type = qtype.qtype_id');
		$q->addQuery('quotations.*, c.company_name as cus_name, stat.status_name, qtype.qtype_name as type_name, stype.stype_name as shipping_type_name, curr.currency_name, supp.sup_name as supplier_name');
		$q->addWhere('quote_id = '.$quoteId);

		$sql = $q->prepare();
		$q->clear();
		$results = db_loadList($sql);

		$q->dropTemp('qtype');
		$q->exec();
		$q->dropTemp('stype');
		$q->exec();
		return $results;
	}

	function getListQuotations($uid, $status = null, $extra = null){
		$q  = new DBQuery;

		$q->createTemp('qtype');
		$q->addTable('md_type');
		$q->addQuery('type_id as qtype_id, name as qtype_name');
		$q->addWhere("type = 'Quotation'");
		$q->exec();
		$q->clear();

		$q  = new DBQuery;
		$q->createTemp('stype');
		$q->addTable('md_type');
		$q->addQuery('type_id as stype_id, name as stype_name');
		$q->addWhere("type = 'ShippingType'");
		$q->exec();
		$q->clear();

		$q  = new DBQuery;
		$q->addTable('quotations');
		$q->innerJoin('companies', 'c', 'quotations.quote_customer = c.company_id');
		$q->leftJoin('md_status', 'stat', 'quotations.quote_status = stat.status_id');
		$q->leftJoin('stype', 'stype', 'quotations.quote_shipping_type = stype.stype_id');
		$q->leftJoin('qtype', 'qtype', 'quotations.quote_type = qtype.qtype_id');
		$q->addQuery('quotations.*, c.company_name as cus_name, stat.status_name, qtype.qtype_name as type_name, stype.stype_name as shipping_type_name');
		if ((null != $status) and (intval($status) > 0)) {
			$q->addWhere('quote_status = '. $status);
		}
		if ((null != $extra) and isset($extra['where']) and ($extra['where'] != '')) {
			$q->addWhere($extra['where']);
		}
		$q->addOrder('c.company_name, quotations.quote_name');
		$results = $q->loadList();
		$q->dropTemp('qtype');
		$q->exec();
		$q->dropTemp('stype');
		$q->exec();
		return $results;
	}

	function getListQuotationByCusId($uid, $status = null, $cusId){
		$extra['where'] = 'quote_customer = '. $cusId;
		return $this->getListQuotations($uid, $status, $extra);
	}

	function getLoadList($uid, $fields='*', $orderby='', $index=null, $extra=null ){
		$q  = new DBQuery;
		$q->addTable('quotations');
		$q->addQuery($fields);
		if ($orderby != ""){
			$q->addOrder($orderby);
		}
		if (''!=$extra['where']){
			$q->addWhere($extra['where']);
		}
		$sql = $q->prepare();
		$q->clear();
		return db_loadList($sql);
	}

	function getAllowedRecords($uid, $fields='*', $orderby='', $index=null, $extra=null ){
		$q  = new DBQuery;
		$q->addTable('quotations');
		if ($extra['where'] != ""){
			$extra['where'] = $extra['where'];
		}
		return parent::getAllowedRecords($uid, $fields, $orderby, $index, $extra);

	}

	function getQuotationByStatusConfimed($uid, $cusId){
		return $this->getLoadList($uid, '*', '', '', 'quote_customer = '.$cusId);
	}

	function updateStatus($uid, $data){
		global $AppUI;
		$fields = array('quote_status', 'quote_completed');
		if(is_array($data)){
			$q = null;
			foreach($data as $item){
				$q  = new DBQuery;
				$q->addTable('quotations');
				$q->addUpdate('quote_status', $item['status']);
				$q->addUpdate('quote_completed', $item['completed']);
				$q->addWhere('quote_id = '.$item['id']);
				$q->exec();
			}
		}
	}

	/**
	 *
	 *
	 * 	Notice: $quote_completed has three 3 status
	 * 		0 : Nothing
	 * 		1 : Active
	 * 		2 : Completed
	 *
	 */
	function store(){
		
		if (intval($this->quote_id) <= 0) {
			//[Customer code]-[Job type]-[Method]-[Year Month]-[Running number]
			$tmp = array ();
			$row = new CCompany();
			$row->load($this->quote_customer);
			$tmp[] .= $row->company_code;

//			$row = new CMdType();
//			$row->load($this->quote_shipping_type);
//			$tmp[] .= $row->code;
			
			$startDate = new CDate(date('Y-m-d'));
			$tmp[] .= $startDate->getMonth();
			$tmp[] .= $startDate->getYear();

			$iso_code_seq = new CSequence();
			$iso_code_seq->seq_key = $this->quote_customer . '-' . $startDate->getMonth() . 'quote_code';
			$iso_code_seq->seq_year = $startDate->getYear();
			$iso_code_seq->loadByField();
			$tmp[] .= $iso_code_seq->useValue();
			// trangdt end

			$this->quote_code = implode('-', $tmp);
		}
		
		// Get id of active, complete
		$active_key = dPgetSysVal(ACTIVE_KEY);
		$comp_key = dPgetSysVal(COMPLETED_KEY);

		// Get code of status
		$objMD = new CMdStatus();
		$objMD->load($this->quote_status);
		$is_active = ($active_key['code'] == $objMD->status_code);
		$is_completed = ($comp_key['code'] == $objMD->status_code);

		if ($is_active) {
			$this->quote_completed = intval(ACTIVE_VAL);
			// Set version
			$this->quote_version = intval($this->quote_version) + 1;
			parent::store();
		}
		else if($is_completed){
			$this->quote_completed = intval(COMPLETED_VAL);
			//unset($this->quote_start_date);
			//unset($this->quote_expire_date);
			parent::store();
		}
		else{
			//$this->quote_start_date = null;
			//$this->quote_expire_date = null;
			parent::store(TRUE);
		}
	}

	/**
     *  Only use autocomplete local
     *
     */

	function getItemsList4AutoCompleter($screen = 'QuotationLine'){
		$iO = new CItem();
		return $iO->getItemsList4AutoCompleter($screen);
	}

	function canDelete(&$msg) {
		if (!parent::canDelete( $msg )) {
			return false;
		}
		$this->load($this->quote_id);
		if ($this->quote_completed) {
			$msg[] = "You can not a delete actived/completed quotation";
			return false;
		}
		return true;
	}
}
?>